package com.jushu.storbox.actions;

import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.Message;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.callback.IUpdateStateChangeListener;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.manager.DownloadTaskManager;
import com.jushu.storbox.manager.UploadTaskManager;
import com.jushu.storbox.service.FileHelper;
import com.jushu.storbox.task.tqueue.DownloadTask;
import com.jushu.storbox.task.tqueue.UploadTask;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.util.UpgradeUtils;
import com.huawei.sharedrive.sdk.android.common.Constants;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.request.ClientInfoResponseV2;
import com.huawei.sharedrive.sdk.android.serviceV2.ApkVersionClientV2;

/**
 * 
 * Share deal class
 * 
 */
public class SettingAction extends BaseAction {

	private final static String TAG = SettingAction.class.getName();


	public void getVersionInfo(final Context context,
			final Handler messageHandler) {
		LogUtil.i(TAG, "getVersionInfo[Actions]");
		executeRunTask(new RealTaskRunnable(context, messageHandler) {
			@Override
			protected void doTask(Context context, Handler msgHandler)
					throws ClientException {
				ClientInfoResponseV2 response = ApkVersionClientV2
						.getInstance().getVerisonInfo(
								ShareDriveApplication.getInstance()
										.getAuthorization());
				Message msg = new Message();
				msg.what = MessageCode.VERSION_INFO_SUCCESS;
				msg.obj = response;
				messageHandler.sendMessage(msg);
			}
		});
	}

	public void logout(final Context context, final Handler messageHandler) {
		LogUtil.i(TAG, "getVersionInfo[Actions]");
		executeRunTask(new RealTaskRunnable(context, messageHandler) {
			@Override
			protected void doTask(Context context, Handler msgHandler)
					throws ClientException {
				String resultStatus = null;
				try{
					resultStatus = ShareDriveApplication.getInstance()
							.getUserClientV2().deleteToken(getAuthCode());
				}catch(Exception e){
				    LogUtil.e("logout fail:" + e.getMessage());
				}
				clear(context);
				Message msg = new Message();
				msg.what = MessageCode.LOGOUT_SUCCESS;
				msg.obj = resultStatus;
				messageHandler.sendMessageDelayed(msg, 1500);
			}

			@Override
			protected void onNetworkUnAvailable(Context context,
					Handler msgHandler) {
				clear(context);
				Message msg = new Message();
				msg.what = MessageCode.LOGOUT_SUCCESS;
				msg.obj = "200";
				messageHandler.sendMessageDelayed(msg, 1500);
				super.onNetworkUnAvailable(context, msgHandler);
			}
			
			
		});
	}

	public void clearCloudDriveCache(final Context context,
			final Handler messageHandler) {
		executeRunTask(new RealTaskRunnable(context, messageHandler) {
			@Override
			protected void doTask(Context context, Handler msgHandler)
					throws ClientException {
				Set<DownloadTask> downloadTasks = DownloadTaskManager
						.getAllTaskes();
				if (downloadTasks != null && downloadTasks.size() > 0) {
					for (DownloadTask task : downloadTasks) {
						task.cancelDownloadTask();
					}
				}
				PublicTools.clearCloudDriveData(context);
				readLocalSpace(context,messageHandler);
			}

			@Override
			protected void onNetworkUnAvailable(Context context,
					Handler msgHandler) {
				PublicTools.clearCloudDriveData(context);
				readLocalSpace(context,messageHandler);
			}
			
		});
	}

	public void loadCacheSize(final Context context,
			final Handler messageHandler) {
		executeRunTask(new RealTaskRunnable(context, messageHandler) {
			@Override
			protected void doTask(Context context, Handler msgHandler)
					throws ClientException {
				readLocalSpace(context,msgHandler);
			}

			@Override
			protected void onNetworkUnAvailable(Context context,
					Handler msgHandler) {
				readLocalSpace(context,msgHandler);
			}
			
		});
	}
	
	private void readLocalSpace(Context context, Handler msgHandler){
		double total = 0;
		try {
			iFileManager mdmTools = FileManagerFactory
					.getFileManager(context);
			total = mdmTools.getCloudDriveSize();
			total += PublicTools.getCloudDriveRMSDocmentSize();
		} catch (Exception e) {
			LogUtil.e(TAG, e.getMessage());
			total = 0;
		}
		String cloudDriveSize = FileHelper.formatFileSize(total);
		String usingSDCardSize = FileHelper.formatFileSize(FileHelper
				.getUsingSDCardSize(context,
						DirectoryUtil.getCurrentCachePath(context)));
		Message msg = new Message();
		msg.what = MessageCode.LOAD_CACHE_SUCCESS;
		msg.obj = new String[] { cloudDriveSize, usingSDCardSize };
		msgHandler.sendMessage(msg);
	}

	private void clear(Context context) {
		// cancel download task
		Set<DownloadTask> downloadTasks = DownloadTaskManager.getAllTaskes();
		if (downloadTasks != null && downloadTasks.size() > 0) {
			for (DownloadTask task : downloadTasks) {
				task.stopDownloadTask();
			}
		}
		// cancel upload task
		Set<UploadTask> uploadTasks = UploadTaskManager.getAllTaskes();
		if (uploadTasks != null && uploadTasks.size() > 0) {
			for (UploadTask task : uploadTasks) {
				task.stopUploadTask();
			}
		}
		SharedPreferences settings = context.getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
		Editor editor = settings.edit();
		editor.putBoolean(ClientConfig.AUTOLOGIN, false);
		PublicTools.setExpiredAt(context, 0l);
		editor.putString(ClientConfig.USERNAME, "");
		PublicTools.setAuthorization(context, "");
		PublicTools.setOwnerId(context, "");
		editor.putString(ClientConfig.LOGINPASSWORD, "");
		editor.putBoolean(ClientConfig.NOT_NEED_NOTIFY, false);//
		PublicTools.setClientUserPassFail(context, "");
		ShareDriveApplication.getInstance().setAuthorization(null);
		ShareDriveApplication.getInstance().setWnerID(null);
		editor.putString(ClientConfig.UAM_ADDRESS, "");
		editor.putString(ClientConfig.UFM_ADDRESS, "");
		editor.commit();
		Constants.UAM_ADDRESS = "";
		Constants.UFM_ADDRESS = "";
	}

	public void upgradeCloudDrive(Context context,
			IUpdateStateChangeListener onUpdateStateChangeListener,
			ClientInfoResponseV2 versionInfo, boolean makeTxt) {

		UpgradeUtils upgradeUtils = new UpgradeUtils(context);
		upgradeUtils.setOnUpdateStateChangeListener(onUpdateStateChangeListener);
		upgradeUtils.upgradeCloudDrive(versionInfo, makeTxt);
	}

}
